package com.csu.bailan.controller;

import com.csu.bailan.common.CONSTANT;
import com.csu.bailan.common.CommonResponse;
import com.csu.bailan.domain.Cart;
import com.csu.bailan.domain.CartItem;
import com.csu.bailan.domain.User;
import com.csu.bailan.dto.CreateOrderDTO;
import com.csu.bailan.service.CartService;
import com.csu.bailan.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Set;

@RestController
@RequestMapping("/cart/")
@Slf4j
public class CartController {
    @Autowired
    private CartService cartService;
    @Autowired
    private OrderService orderService;

    @PostMapping("addtocart")
    public CommonResponse<String> addtocart(String skuid, HttpSession session){
        User loginUser = (User) session.getAttribute(CONSTANT.LOGIN_USER);
        int item_num = (Integer) session.getAttribute(CONSTANT.item_num);
        if(loginUser == null){
            return CommonResponse.createForError("用户未登录");
        }
        if(cartService.createCart(loginUser.getUserId())){
            if(cartService.addtocart(skuid,loginUser.getUserId(),item_num)){
                return CommonResponse.createForSuccess("添加购物车成功");
            }
            return CommonResponse.createForSuccess("添加购物车失败");
        }
        return CommonResponse.createForError("添加购物车失败");

    }

    @GetMapping("mycart")
    public CommonResponse<List> cartItemList(HttpSession session){
        User loginUser = (User) session.getAttribute(CONSTANT.LOGIN_USER);
        if(loginUser == null){
            return CommonResponse.createForError("用户未登录");
        }
        Cart cart = cartService.getCartByUserId(loginUser.getUserId());
        List<CartItem> cartItemList = cartService.getCIByCartId(cart.getCartId());
        return CommonResponse.createForSuccess(cartItemList);
    }

    @PostMapping("deletecartitem")
    public CommonResponse<String> deletecartitem(Set<String> citem_id, HttpSession session){
        User loginUser = (User) session.getAttribute(CONSTANT.LOGIN_USER);
        if(loginUser == null){
            return CommonResponse.createForError("用户未登录");
        }
        if(cartService.deleteCartItem(citem_id)){
            return CommonResponse.createForSuccess("删除成功");
        }
        return CommonResponse.createForError("删除失败");
    }

    @PostMapping("cartpay")
    public CommonResponse<String> payforcart(@RequestBody CreateOrderDTO createOrderDTO, HttpSession session){
        User loginUser = (User) session.getAttribute(CONSTANT.LOGIN_USER);
        if(loginUser == null){
            return CommonResponse.createForError("用户未登录");
        }
        if(orderService.createOrder(createOrderDTO, loginUser.getUserId())) {
            return CommonResponse.createForSuccess();
        }
        return CommonResponse.createForError("创建订单失败");

    }
}

